

package com.maoshi.shop.multishop.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.maoshi.shop.bean.enums.OrderStatus;
import com.maoshi.shop.bean.model.*;
import com.maoshi.shop.bean.param.DeliveryOrderParam;
import com.maoshi.shop.bean.param.OrderParam;
import com.maoshi.shop.common.annotation.SysLog;
import com.maoshi.shop.common.exception.MaoshiShopBindException;
import com.maoshi.shop.common.util.Arith;
import com.maoshi.shop.common.util.PageParam;
import com.maoshi.shop.security.multishop.util.SecurityUtils;
import com.maoshi.shop.service.*;
import org.apache.ibatis.type.ArrayTypeHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lgh on 2018/09/15.
 */
@Controller
@RequestMapping("/order/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private UserAddrOrderService userAddrOrderService;

    @Autowired
    private ProductService productService;

    @Autowired
    private SkuService skuService;

    @Autowired
    private OrderRefundService orderRefundService;

    /**
     * 分页获取
     */
    @GetMapping("/page")
    public ResponseEntity<IPage<Order>> page(OrderParam orderParam,PageParam<Order> page) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        orderParam.setShopId(shopId);
        IPage<Order> orderIPage = orderService.pageOrdersDetialByOrderParam(page, orderParam);
        return ResponseEntity.ok(orderIPage);
    }

    /**
     * 获取信息
     */
    @GetMapping("/orderInfo/{orderNumber}")
    public ResponseEntity<Order> info(@PathVariable("orderNumber") String orderNumber) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        Order order = orderService.getOrderByOrderNumberAndShopId(orderNumber,shopId,true);
        List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(orderNumber);
        order.setOrderItems(orderItems);
        UserAddrOrder userAddrOrder = userAddrOrderService.getById(order.getAddrOrderId());
        order.setUserAddrOrder(userAddrOrder);
        return ResponseEntity.ok(order);
    }

    /**
     * 发货
     */
    @PutMapping("/delivery")
    public ResponseEntity<Void> delivery(@RequestBody DeliveryOrderParam deliveryOrderParam) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        Order order = orderService.getOrderByOrderNumberAndShopId(deliveryOrderParam.getOrderNumber(),shopId,true);
        if (!Objects.equals(order.getStatus(), OrderStatus.PADYED.value())){
            throw new MaoshiShopBindException("订单不处于待发货状态，无法进行发货");
        }
        List<OrderRefund> orderRefunds = orderRefundService.getProcessingOrderRefundByOrderId(order.getOrderId());

        if (CollectionUtil.isNotEmpty(orderRefunds)) {
            throw new MaoshiShopBindException("该订单有退款信息正在处理当中，请处理完毕之后再进行发货的操作！");
        }

        Order orderParam = new Order();
        orderParam.setOrderId(order.getOrderId());
        orderParam.setDvyId(deliveryOrderParam.getDvyId());
        orderParam.setDvyFlowId(deliveryOrderParam.getDvyFlowId());
        orderParam.setDvyTime(new Date());
        orderParam.setUpdateTime(new Date());
        orderParam.setStatus(OrderStatus.CONSIGNMENT.value());
        orderParam.setUserId(order.getUserId());

        orderService.delivery(orderParam);

        List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(deliveryOrderParam.getOrderNumber());
        for (OrderItem orderItem : orderItems) {
            productService.removeProductCacheByProdId(orderItem.getProdId());
            skuService.removeSkuCacheBySkuId(orderItem.getSkuId(),orderItem.getProdId());
        }
        return ResponseEntity.ok().build();
    }
    /**
     * 修改订单金额
     */
    @PutMapping("/changeAmount")
    public ResponseEntity<Void> changeAmount(@RequestBody Order order) {
        if(order.getFreightAmount()<0){
            throw new MaoshiShopBindException("运费不能小于零");
        }
        if(Objects.isNull(order.getFreightAmount())){
            order.setFreightAmount(0.00);
        }
        orderService.changeAmount(order);
        return ResponseEntity.ok().build();
    }

    /**
     * 修改用户订单地址
     *
     * @param order
     * @return 是否修改成功
     */
    @SysLog("修改用户订单地址")
    @PutMapping("/changeUserAddr")
    public ResponseEntity<String> changeUserAddr(@RequestBody @Valid Order order) {
        Order orderDb = orderService.getOne(new LambdaQueryWrapper<Order>()
                .eq(Order::getOrderId, order.getOrderId())
                .eq(Order::getOrderNumber,order.getOrderNumber())
        );
        if (orderDb.getStatus() <= OrderStatus.PADYED.value() || Objects.equals(orderDb.getStatus(),OrderStatus.WAIT_GROUP.value())){
            UserAddrOrder userAddrOrder = order.getUserAddrOrder();
            userAddrOrderService.updateById(userAddrOrder);
        }else {
            throw new MaoshiShopBindException("订单状态异常，无法更改订单地址");
        }
        return ResponseEntity.ok().body("修改成功");
    }

    /**
     * 修改订单备注
     *
     * @param order
     * @return 是否修改成功
     */
    @SysLog("修改订单备注")
    @PutMapping("/changeOrderRamark")
    public ResponseEntity<String> changeOrderRamark(@RequestBody @Valid Order order) {
        Order orderDb = orderService.getOne(new LambdaQueryWrapper<Order>()
                .eq(Order::getOrderId, order.getOrderId())
                .eq(Order::getOrderNumber,order.getOrderNumber())
        );
        orderDb.setShopRemarks(order.getShopRemarks());
        orderService.updateById(orderDb);
        return ResponseEntity.ok().body("修改成功");
    }

    /**
     * 已销售订单
     *
     * @param orderParam
     */
    @GetMapping("/soldExcel")
    public void soldExcel(OrderParam orderParam, HttpServletResponse response) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        orderParam.setShopId(shopId);
//        orderParam.setIsPayed(1);
        orderService.soldExcel(orderParam,response);

//        //通过工具类创建writer
//        ExcelWriter writer = ExcelUtil.getWriter();
//        // 待发货
//        String[] hearder = {"订单编号", "订单状态", "下单时间", "收件人", "手机", "收货地址", "商品名称", "数量", "订单应付", "订单运费", "订单实付"};
//        Sheet sheet = writer.getSheet();
//        sheet.setColumnWidth(0, 20 * 256);
//        sheet.setColumnWidth(2, 20 * 256);
//        sheet.setColumnWidth(4, 20 * 256);
//        sheet.setColumnWidth(5, 60 * 256);
//        sheet.setColumnWidth(6, 60 * 256);
//
//        writer.merge(hearder.length - 1, "销售信息整理");
//        writer.writeRow(Arrays.asList(hearder));
//
//        int row = 1;
//        for (Order dbOrder : orders) {
//            UserAddrOrder addr = dbOrder.getUserAddrOrder();
//            String addrInfo = addr.getProvince() + addr.getCity() + addr.getArea() + addr.getAddr();
//            List<OrderItem> orderItems = dbOrder.getOrderItems();
//            int firstRow = row + 1;
//            int lastRow = row + orderItems.size();
//            int col = -1;
//            // 订单编号
//            mergeIfNeed(writer, firstRow, lastRow, ++col, col, dbOrder.getOrderNumber());
//            //订单状态
//            String status = "";
//            switch (dbOrder.getStatus()){
//                case 1: status = "待付款"; break;
//                case 2: status = "待发货"; break;
//                case 3: status = "待收货"; break;
//                case 4: status = "待评价"; break;
//                case 5: status = "成功"; break;
//                case 6: status = "失败"; break;
//                case 7: status = "待成团"; break;
//                default: status = "";
//            }
//            if (!Objects.isNull(dbOrder.getRefundStatus())){
//                switch (dbOrder.getRefundStatus()){
//                    case 1: status = "申请退款"; break;
//                    case 2: status = "退款成功"; break;
//                    case 3: status = "退款成功"; break;
//                    default: break;
//                }
//            }
//            mergeIfNeed(writer, firstRow, lastRow, ++col, col, status);
//            // 下单时间
//            mergeIfNeed(writer, firstRow, lastRow, ++col, col, dbOrder.getCreateTime());
//            // 收件人
//            mergeIfNeed(writer, firstRow, lastRow, ++col, col, addr.getReceiver());
//            // "手机"
//            mergeIfNeed(writer, firstRow, lastRow, ++col, col, addr.getMobile());
//            // "收货地址"
//            mergeIfNeed(writer, firstRow, lastRow, ++col, col, addrInfo);
//            int prodNameCol = ++col;
//            int prodCountCol = ++col;
//            for (OrderItem orderItem : orderItems) {
//                row++;
//                // 商品名称
//                writer.writeCellValue(prodNameCol, row, orderItem.getProdName());
//                // 数量
//                writer.writeCellValue(prodCountCol, row, orderItem.getProdCount());
//            }
//            // 订单应付
//            mergeIfNeed(writer, firstRow, lastRow, ++col, col, dbOrder.getTotal());
//            // 订单运费
//            mergeIfNeed(writer, firstRow, lastRow, ++col, col, dbOrder.getFreightAmount());
//            // 订单实付
//            mergeIfNeed(writer, firstRow, lastRow, ++col, col, dbOrder.getActualTotal());
//
//        }
//        writeExcel(response, writer);
    }

//    /**
//     * 如果需要合并的话，就合并
//     */
//    private void mergeIfNeed(ExcelWriter writer, int firstRow, int lastRow, int firstColumn, int lastColumn, Object content) {
//        if (lastRow - firstRow > 0 || lastColumn - firstColumn > 0) {
//            writer.merge(firstRow, lastRow, firstColumn, lastColumn, content, false);
//        } else {
//            writer.writeCellValue(firstColumn, firstRow, content);
//        }
//
//    }
//
//    private void writeExcel(HttpServletResponse response, ExcelWriter writer) {
//        //response为HttpServletResponse对象
//        response.setContentType("application/vnd.ms-excel;charset=utf-8");
//        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
//        response.setHeader("Content-Disposition", "attachment;filename=1.xls");
//
//        ServletOutputStream servletOutputStream = null;
//        try {
//            servletOutputStream = response.getOutputStream();
//            writer.flush(servletOutputStream);
//            servletOutputStream.flush();
//        } catch (IORuntimeException | IOException e) {
//            e.printStackTrace();
//        } finally {
//            writer.close();
//            try {
//                if (servletOutputStream != null) {
//                    servletOutputStream.close();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//    }
}
